package my.poemlib.dao;

import my.poemlib.vo.PageControl;
import my.poemlib.vo.Poem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Component;

@Component
public class PoemDaoImpl implements PoemDao{
	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public void insertPeom(Poem p) {
		String sql = "INSERT INTO poem (title,author,topic,age,type,content,inserttime)VALUES('"+p.getTitle()+"','"+p.getAuthor()+"','"+p.getTopic()+"','"+p.getAge()+"','"+p.getType()+"','"+
		(p.getTitle()+"|"+p.getAgeStr()+"|"+p.getTopicStr()+"|"+p.getTypeStr()+"##"+p.getContent())+"',UNIX_TIMESTAMP());";
		jdbcTemplate.execute(sql);
	}

	@Override
	public void delPeom(long id) {
		String sql = "delete from poem where id="+id;
		jdbcTemplate.execute(sql);
	}

	@Override
	public void queryByWord(String w,PageControl pc) {
		String coutSql = "select count(1) from poem";
		int count = jdbcTemplate.queryForInt(coutSql);
		pc.getPoemList().clear();
		pc.setTotalPage(count/pc.getPageSize()+(count%pc.getPageSize()==0?0:1));
		
		
		StringBuilder sql = new StringBuilder("select * from poem");
		if(w!=null && !"".equals(w)){
			w.replace("##", "");
			sql.append(" where  content like '%"+w+"%'");
		}
		sql.append(" order by inserttime");
		sql.append(" limit ").append((pc.getCurrentPage()-1)*pc.getPageSize()).append(",").append(pc.getPageSize());
		
		SqlRowSet rs = jdbcTemplate.queryForRowSet(sql.toString());
		while(rs.next()){
			Poem p = new Poem();
			p.setTitle(rs.getString("title"));
			p.setTopic(rs.getInt("topic"));
			p.setType(rs.getInt("type"));
			p.setAge(rs.getInt("age"));
			p.setAuthor(rs.getString("author"));
			p.setId(rs.getLong("id"));
			String content = rs.getString("content");
			if(content!=null && !"".equals(content) && content.indexOf("##")>0){
				int index = content.indexOf("##");
				if(content.length()>index+2);
				content = content.substring(index+2);
			}
			p.setContent(content);
			pc.getPoemList().add(p);
		}
	}
}
